package com.lb.bigdata.spark.p1;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

/**
 * spark入门案例之java版
 *  编程入口：SparkContext，但是java版本为JavaSparkContext
 *  同时不同的spark模块的编程入口有所差异：
 *      SQL中的模块：
 *              早期版本为SQLContext和HiveContext
 *              2.0之后统一为SparkSesson
 *      Streaming中：
 *            java： JavaStreamingContext
 *            scala：StreamingContext
 *  编程通用的步骤：
 *  1、构建编程入口XxxContext
 *      需要涉及相应的配置信息
 *  2、加载外部数据
 *  3、对加载的数据进行转换操作、
 *  4、要提交spark作业的执行
 *  5、释放资源
 */
public class JavaWordCountOps {
    public static void main(String[] args) {
        //相当于mr中的Configuration
        SparkConf conf = new SparkConf();
        conf.setAppName("JavaWordCount");
        conf.setMaster("local[*]");
        //jsc相当于mr中的job
        JavaSparkContext jsc = new JavaSparkContext(conf);

        JavaRDD<String> linesRDD = jsc.textFile("D:/a.txt");

        JavaRDD<String> wordsRDD = linesRDD.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterator<String> call(String line) throws Exception {
                String[] split = line.split("\\s+");
                return Arrays.asList(split).iterator();
            }
        });

        JavaPairRDD<String, Integer> pairRDD = wordsRDD.mapToPair(new PairFunction<String, String, Integer>() {
            @Override
            public Tuple2<String, Integer> call(String s) throws Exception {
                return new Tuple2<String, Integer>(s, 1);
            }
        });

        JavaPairRDD<String, Integer> ret = pairRDD.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        ret.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            @Override
            public void call(Tuple2<String, Integer> kv) throws Exception {
                System.out.printf("word: %s, count: %d\n", kv._1, kv._2);
            }
        });
    }
}
